# 0. Setup ----
library(data.table)
library(laeken) # weighted quantiles
library(xtable) 

main_dir <- "DATADIR"

hh_pp <- readRDS(paste0(main_dir, "usoc_hh_with_ind_vars.RDS")) # household file with individual char



# 1. restricting the sample ---- 

hh_pp[, mywave := wave - 18] # remove old BHPS waves

dt <- hh_pp[mywave == 6]



# 2. Create age bands ----

# Take the same age bands as in 
# https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/895386/NS_Table_3_2_1718.xlsx

agebreaks <-
  c(0, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 150)
agelabels <-
  factor(
    c(
      "Under 20",
      "20-24",
      "25-29",
      "30-34",
      "35-39",
      "40-44",
      "45-49",
      "50-54",
      "55-59",
      "60-64",
      "65-69",
      "70-74",
      "75 and over"
    ),
    ordered = T
  )

dt[, `:=`(agegroup,
          cut(
            head_age,
            breaks = agebreaks,
            right = FALSE,
            labels = agelabels
          ))]


# 3. Run stats on everyone ----

dt[fihhmngrs_dv >= 0, hh_inc := fihhmngrs_dv * 12]

pct <- c(
  "5th pct" = .05,
  "10th pct" = .1,
  "25th pct" = .33,
  "Median" = .5,
  "75th pct" = .66,
  "90th pct" = .9,
  "95th pct" = .95
)
n <- dt[, .N, by = agegroup]

t <-
  dt[, lapply(pct, function(x)
    weightedQuantile(
      hh_inc,
      probs = x,
      na.rm = T,
      weights = hhdenub_xw
    )), by = agegroup]

tab <- merge(t, n, by = "agegroup")

print(xtable(tab, digits = 0), only.contents = TRUE, hline.after = NULL, 
      include.colnames = FALSE, include.rownames = FALSE, 
      file = paste0(TABLEDIR, "hh_inc_pct_w.tex"))


# 4. Run stats on mortgagors ----
n <- dt[tenure_dv == 2, .N, by = agegroup]

t <-
  dt[tenure_dv == 2, lapply(pct, function(x)
    weightedQuantile(
      hh_inc,
      probs = x,
      na.rm = T,
      weights = hhdenub_xw
    )), by = agegroup]

tab <- merge(t, n, by = "agegroup")

print(xtable(tab, digits = 0), only.contents = TRUE, hline.after = NULL, 
      include.colnames = FALSE, include.rownames = FALSE, 
      file = paste0(TABLEDIR, "hh_inc_pct_mw.tex"))
